package com.heimachefu.module.user.controller;

import com.heimachefu.common.BaseController;
import com.heimachefu.common.CommonUtils;
import com.heimachefu.common.Result;
import com.heimachefu.module.user.check.UpdateOrRemoveGroup;
import com.heimachefu.module.user.check.UserParam;
import com.heimachefu.module.user.entity.UserEntity;
import com.heimachefu.module.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author liuxingdong@heimachefu.com
 * @date 2019/7/19 11:30
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {


    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }


    @RequestMapping("/loginPage")
    public String loginPage(){
        return "app/login";
    }

    @PostMapping("/login")
    public String login(){
        return "";
    }

    @GetMapping("/list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView("app/user/user_list");
        modelAndView.addObject("userList",userService.getAuthResourceListForUser(getRequestUser().getUserId()));
        return modelAndView;
    }


    /**
     * 获取账号信息列表
     * @return
     */
    @RequestMapping("/page")
    public ModelAndView page(UserParam userParam){
        ModelAndView modelAndView = new ModelAndView("app/user/user_list");
        userParam.setPageNo(0);
        userParam.setPageSize(10);
        Page<UserEntity> userEntityPage = userService.list(userParam);
        modelAndView.addObject("userList",userEntityPage);
        return modelAndView;
    }

    /**
     * 删除用户
     * @param userParam
     * @param bindingResult
     * @return
     */
    @DeleteMapping("/remove")
    @ResponseBody
    public Result remove(@Validated(value = UpdateOrRemoveGroup.class)UserParam userParam , BindingResult bindingResult){
        if(!bindingResult.hasErrors()){
            return userService.remove(userParam.getUserId());
        }else {
            return CommonUtils.error(bindingResult.getFieldErrors().get(0).getDefaultMessage());
        }
    }


}
